package com.uic.server;

import com.uic.client.GreetingService;
import com.uic.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {

  public String greetServer(String input) throws IllegalArgumentException {
    // Verify that the input is valid. 
    if (!FieldVerifier.isValidName(input)) {
      // If the input is not valid, throw an IllegalArgumentException back to
      // the client.
      throw new IllegalArgumentException("Name must be at least 4 characters long");
    }

    // Escape data from the client to avoid cross-site script vulnerabilities.
    input = escapeHtml(input);

    // Select command from if-else. Switch-statement may be implemented
    // when i found a way to link strings to functions.
    return selectCommand(input);
   

  }
  
  // Selects command to be run
  private String selectCommand(String command) {
	if (command.equals("help")) {
    	return "cli user guide:<br/>" +
    			"Try commands like <b>serverinfo</b> or <b>userinfo</b>";
    } else if (command.equals("serverinfo")) {
    	return serverInfo();
    } else if (command.equals("userinfo")) {
    	return userAgent();
    } else {
    	return "Unknown command";
    }
  }
  
  // prints server info
  public String serverInfo() {
	  String server = getServletContext().getServerInfo();
	  return server;
  }
  
  // prints user info
  public String userAgent() {
	  String user = getThreadLocalRequest().getHeader("User-Agent");
	  user = escapeHtml(user);
	  return user;
  }
  
  
  /**
   * Escape an html string. Escaping data received from the client helps to
   * prevent cross-site script vulnerabilities.
   * 
   * @param html the html string to escape
   * @return the escaped string
   */
  private String escapeHtml(String html) {
    if (html == null) {
      return null;
    }
    return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
  }
}
